<template>
  <el-dialog :model-value="dialogVisible" :title="dialogDatas.title" :destroy-on-close="true" @close="closeDialog">
    <div>
      <el-form style="height:480px;overflow: auto;" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :disabled="dialogDatas?.type == 'check'">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName" placeholder="请输入角色名称" clearable maxlength="10" />
        </el-form-item>
        <el-form-item label="所属机构" prop="orgId">
          <el-select v-model="ruleForm.orgId"  :disabled="dialogDatas?.type == 'edit'" class="w-full" placeholder="请选择所属机构" v-if="showOrg">
            <el-option v-for="(item) in orgIdDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入角色描述" type="textarea" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="功能权限" prop="menuIdList">
          <div v-for="item in dialogConfig?.menuListMap" :key="item.id" class="border border-slate-300 p4 w-full mb4">
            <div class="flex">
              <p class="font-medium pr2">{{ item.menuName }}</p>
              <el-checkbox label="导航菜单或列表页" v-model="item.isCheck" @change="checkboxChange(item)" />
            </div>
            <el-checkbox v-for="childrenItem in item.children" :key="childrenItem.id" :disabled="!item.isCheck"
              :label="childrenItem.menuName" :checked="childrenItem.isCheck" v-model="childrenItem.isCheck" />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    <template #footer v-if="(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onBeforeMount, toRefs } from 'vue';
import { menuListRequest, orgOptionsRequest } from '@/api/common';
import type { FormInstance, FormRules } from 'element-plus';
import { roleAddRequest, roleViewRequest, roleEditRequest } from '@/api/system/role/index';//api
import { useUserStore } from '@/store';
const userStore = useUserStore();
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible']);
const visible = ref(false);
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const { dialogVisible, dialogDatas } = toRefs(props);
const init = (data: any) => {
  // if (data) dialogDatas.value = JSON.parse(JSON.stringify(data));
};
defineExpose({ init });
let dialogConfig = ref<any>({});//权限变量
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: null,
  roleName: '',
  orgId: '',
  remark: '',
  menuIdList: []
})
// 校验
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'change' }],
  orgId	: [{ required: true, message: '选择归属组织', trigger: 'change' }]
})
//提交
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let menuIds: any = [];
      dialogConfig.value.menuListMap.forEach((it: any) => {
        if (it.isCheck) {
          menuIds.push(it.id)
        }
        it.children.forEach((children: any) => {
          if (children.isCheck) {
            menuIds.push(children.id)
          }
        })
      })
      ruleForm.menuIdList = menuIds
      let Url = dialogDatas.value.type == 'add' ? roleAddRequest : roleEditRequest;
      let res: any = await Url(ruleForm);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);
      } else {
        ElMessage.error(res.message)
      }
      formEl.resetFields()//重置
      emit('updateList')
    } else {
      console.log('保存失败', fields)
    }
  })
}
// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}
// 权限按钮list
const getMenuList = async () => {
  const data: any = await menuListRequest({ orgId: userStore.userInfo.orgId });
  dialogConfig.value = Object.assign({}, data.data);
};

const checkboxChange = (item: any) => {
  item.children.forEach((i: any) => {
    i.isCheck = !item.isCheck ? false : i.isCheck
  });
};
// 所属机构下拉
let orgIdDatas = reactive([])
let showOrg = ref(true)
const getOrgOptionsDatas = async () => {
  showOrg.value = false
  const data: any = await orgOptionsRequest({ containBase: true });
  orgIdDatas = data.data;
  showOrg.value = true
};
// 获取详情
const getDetailsFun = async () => {
  const data: any = await roleViewRequest({ id: dialogDatas.value.datas.id });
  let res = data.data
  ruleForm.id = res.id
  ruleForm.roleName = res.roleName
  ruleForm.orgId = res.orgId
  ruleForm.remark = res.remark
  dialogConfig.value = res.menuIdList
}
onBeforeMount(async () => {
  await getOrgOptionsDatas()
  if (dialogDatas.value.type == 'add') {
    getMenuList()
  } else {
    getDetailsFun()
  }
})
</script>

<style lang="scss" scoped>
.el-dialog__footer{
  text-align: center;
}
</style>
